package admin

import (
	"go-weiqi-system/config"
	"go-weiqi-system/internal/models"
	"go-weiqi-system/internal/utils"

	"github.com/gin-gonic/gin"
)

type CompetitionRegistrationController struct{}

// Index 比赛报名列表
func (ctrl *CompetitionRegistrationController) Index(c *gin.Context) {
	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	competitionID := c.Query("competition_id")
	status := c.Query("status")

	var registrations []models.CompetitionRegistration
	var total int64

	db := config.DB.Model(&models.CompetitionRegistration{}).
		Preload("User").
		Preload("Competition")

	if competitionID != "" {
		db = db.Where("competition_id = ?", competitionID)
	}
	if status != "" {
		db = db.Where("status = ?", status)
	}

	db.Count(&total)
	db.Order("id desc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&registrations)

	utils.Success(c, models.PageResponse{
		List:     registrations,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// Detail 报名详情
func (ctrl *CompetitionRegistrationController) Detail(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		utils.Error(c, "参数错误")
		return
	}

	var registration models.CompetitionRegistration
	if err := config.DB.Preload("User").Preload("Competition").
		First(&registration, id).Error; err != nil {
		utils.Error(c, "报名记录不存在")
		return
	}

	utils.Success(c, registration)
}

// UpdateStatus 更新状态
func (ctrl *CompetitionRegistrationController) UpdateStatus(c *gin.Context) {
	var req struct {
		ID     uint   `json:"id" binding:"required"`
		Status string `json:"status" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, "参数错误")
		return
	}

	if err := config.DB.Model(&models.CompetitionRegistration{}).
		Where("id = ?", req.ID).
		Update("status", req.Status).Error; err != nil {
		utils.Error(c, "更新失败")
		return
	}

	utils.Success(c, nil, "更新成功")
}

// Statistics 统计
func (ctrl *CompetitionRegistrationController) Statistics(c *gin.Context) {
	competitionID := c.Query("competition_id")

	var totalCount int64
	var confirmedCount int64
	var pendingCount int64

	db := config.DB.Model(&models.CompetitionRegistration{})
	if competitionID != "" {
		db = db.Where("competition_id = ?", competitionID)
	}

	db.Count(&totalCount)
	db.Where("status = ?", "已确认").Count(&confirmedCount)
	db.Where("status = ?", "待确认").Count(&pendingCount)

	utils.Success(c, gin.H{
		"total_count":     totalCount,
		"confirmed_count": confirmedCount,
		"pending_count":   pendingCount,
	})
}

// Export 导出
func (ctrl *CompetitionRegistrationController) Export(c *gin.Context) {
	competitionID := c.Query("competition_id")

	var registrations []models.CompetitionRegistration
	db := config.DB.Preload("User").Preload("Competition")

	if competitionID != "" {
		db = db.Where("competition_id = ?", competitionID)
	}

	db.Find(&registrations)

	utils.Success(c, registrations, "导出成功")
}
